package pri.damai.xiaowu.common.security.config;

import cn.hutool.core.collection.CollectionUtil;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 *
 * @Desc
 * @Author DaMai
 * @Date 2021/7/15 11:14
 * 但行好事，莫问前程。
 */
@RefreshScope
@Component
@ConfigurationProperties("xiaowu.security")
@Data
public class XiaoWuSecurityProperties {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    /** 令牌密钥 */
    private String jwtSecret = "damaidamaidamaidamaidamai";

    /** token 的 redis-key 前缀 */
    private String tokenRedisKey = "AUTH:TOKEN:";

    /** 令牌过期时间(分钟) */
    private Long expiration = 60 * 24 * 30L;

    /** 刷新令牌过期时间: 默认是令牌过期时间的两倍 */
    private Long refreshExpiration = expiration * 2;

    /** 默认请求间隔过期时间: 3600 秒 */
    private Long expirationInterval = 3600L;

    /** 登录接口 Url */
    private String loginUrl = "/login";

    /** 登出接口 Url */
    private String logoutUrl = "/logout";

    /** 无需认证即可访问的地址 */
    private List<String> notLoginUrls = new ArrayList<>();

    /** 无需鉴权即可访问的地址 */
    private List<String> notAuthUrls = new ArrayList<>();

    /** 需放行的前端静态资源地址 */
    private List<String> staticResourceUrls = Arrays.asList("/css/**", "/js/**", "/index.html", "/img/**",
            "/fonts/**", "/favicon.ico");

    public String getUserTokenKey(Integer userId) {
        if (Objects.isNull(userId)) {
            return "";
        }
        return this.tokenRedisKey + userId;
    }

    public boolean isNoLoginPass(String realPath) {
        return this.isPass(this.notLoginUrls, realPath);
    }

    public boolean isNotAuthPass(String readPath) {
        return this.isPass(this.notAuthUrls, readPath);
    }

    /**
     * 是否放行
     * @apiNote [附加描述]
     * @param realPath 真实地址
     * @return boolean
     * @author DaMai
     * @date 2022/3/1 19:42
     */
    private boolean isPass(List<String> urlList, String realPath) {
        if (CollectionUtil.isEmpty(urlList)) {
            return false;
        }
        return urlList.stream().anyMatch(s -> PATH_MATCHER.match(s, realPath));
    }


}
